package com.yt.fras.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:RedisConfig
 * Package:com.yt.fras.config
 * Description:
 * Redis配置
 *
 * @date:2021/9/30 16:05
 * @author:yt
 */

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;


    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(redisHost);
        configuration.setPort(redisPort);
        configuration.setPassword(redisPassword);
        configuration.setDatabase(0);
        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration);
        return factory;
    }


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        /*
         * 序列化设置
         */
        // key、hash的key 采用 String序列化方式
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // value、hash的value 采用 Jackson 序列化方式
        template.setValueSerializer(RedisSerializer.json());
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();
        return template;
    }

    @Override
    public CacheResolver cacheResolver() {
        return new SimpleCacheResolver(cacheManager());
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return new SimpleCacheErrorHandler();
    }

    @Override
    @Bean
    public CacheManager cacheManager() {
        Map<String, RedisCacheConfiguration> cacheConfigurations = generateCacheConfigMap();
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .disableCachingNullValues().serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(redisConnectionFactory()).cacheDefaults(cacheConfiguration)
                .withInitialCacheConfigurations(cacheConfigurations).build();
    }

    private Map<String, RedisCacheConfiguration> generateCacheConfigMap() {
        // 针对不同cacheName，设置不同的过期时间
        Map<String, RedisCacheConfiguration> initialCacheConfiguration = new HashMap<>();
        initialCacheConfiguration.put("userCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
        initialCacheConfiguration.put("userRoleCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
        initialCacheConfiguration.put("permissionCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1)));
        initialCacheConfiguration.put("managementGroupCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
        initialCacheConfiguration.put("groupUserCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
        initialCacheConfiguration.put("attendanceCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
        initialCacheConfiguration.put("attendanceUserCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
        return initialCacheConfiguration;
    }


}
